var rp = require('request-promise');
const urls = require("../utils")


const fs = require("fs")
const path = require("path")
const util = require("util")
const unlink = util.promisify(fs.unlink)

const { uploadFile } = require("tools-factory-tang")
const addPostImgs = async req => {
    const { data: { _id, url } } = await uploadFile(req);
    console.log(_id, url);
    // const token = req.headers["authorization"];
    // console.log(token);
    var options = {
        method: 'patch',
        uri: `${urls["api-server"]}/movies/${_id}/imgs/${encodeURIComponent(url)}`,
        // headers: {
        //     "authorization": token
        // },
        json: true // Automatically stringifies the body to JSON
    };
    const data = await rp(options)
    return data
}
const addSetImgs = async req => {
    const { data: { _id, url } } = await uploadFile(req);
    console.log(_id, url);
    // const token = req.headers["authorization"];
    // console.log(token);
    var options = {
        method: 'patch',
        uri: `${urls["api-server"]}/movies/${_id}/setImg/${encodeURIComponent(url)}`,
        // headers: {
        //     "authorization": token
        // },
        json: true // Automatically stringifies the body to JSON
    };
    const data = await rp(options)
    return data
}
const addHeadImgs = async req => {
    const { data: { _id, url } } = await uploadFile(req);
    console.log(_id, url);
    // const token = req.headers["authorization"];
    // console.log(token);
    var options = {
        method: 'patch',
        uri: `${urls["api-server"]}/movies/${_id}/headImg/${encodeURIComponent(url)}`,
        // headers: {
        //     "authorization": token
        // },
        json: true // Automatically stringifies the body to JSON
    };
    const data = await rp(options)
    return data
}

const deleteImg = async url => {
    const imgUrl = path.join(path.resolve(__dirname, "../public"), url);
    try {
        await unlink(imgUrl)
    } catch (error) {
        return { statue: false }
    }
    return { statue: true }
}

module.exports = { addPostImgs,addSetImgs,addHeadImgs, deleteImg}